﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Gpsys.Entity.MSG;
using Gpsys.Web.Business;
using System.Web.Mvc;
using Gpsys.Interface;
using Gpsys.Common.Helper;

namespace Gpsys.Web.Models
{
    public class PortEntityModel
    {
        public Port Port { get; set; }

        public List<SelectListItem> GetAdapterTypeItems()
        {
            AdapterBusiness bs = new AdapterBusiness();

            return bs.GetAdapterCodes().Select(s => new SelectListItem()
            {
                Text = s,
                Value = s
            }).ToList();
        }

        public string GetAdapterXml(string code, int type)
        {
            AdapterBusiness bs = new AdapterBusiness();

            var ad = bs.GetAdapter(code, type);

            if (ad != null)
            {
                var confType = Type.GetType(ad.ConfigurationClassType);

                IConfiguration conf = Activator.CreateInstance(confType) as IConfiguration;

                if (conf != null)
                {
                    conf.CreateDefault();
                    return XmlHelper.SerializeToXml(conf);
                }
            }

            return string.Empty;
        }
    }

    public class PortModel
    {
        public bool InsertPort(Port tr)
        {
            PortBusiness bs = new PortBusiness();

            return bs.InsertPort(tr);
        }

        public bool UpdatePort(Port tr)
        {
            PortBusiness bs = new PortBusiness();

            return bs.UpdatePort(tr);
        }

        public Port GetPort(int Id)
        {
            PortBusiness bs = new PortBusiness();

            return bs.GetPort(Id);
        }

        public void DeletePort(int Id)
        {
            PortBusiness bs = new PortBusiness();

            bs.DeletePort(Id);
        }

        private List<Port> m_Ports;

        public List<Port> Ports
        {
            get
            {
                if (m_Ports == null)
                {
                    PortBusiness bs = new PortBusiness();
                    m_Ports = bs.GetPorts();
                }
                return m_Ports;
            }
        }

        public void ValidatePort(ModelStateDictionary modelState, PortEntityModel model)
        {
            if (string.IsNullOrEmpty(model.Port.Code))
                modelState.AddModelError("Port.Code", "Code could not be empty.");

            if (string.IsNullOrEmpty(model.Port.Configuration))
                modelState.AddModelError("Port.Configuration", "Configuration could not be empty.");

            PortBusiness bs = new PortBusiness();
            if (bs.CheckCodeUsed(model.Port))
            {
                modelState.AddModelError("Port.Code", "Code is already been used.");
            }
        }
    }
}